package com.example.concurrency.day5;

import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 请结合ReentrantLock、Condition实现一个简单的阻塞队列，阻塞队列提供两个方法，一个是put、一个是take
 *
 * 当队列为空时，请求take会被阻塞，直到队列不为空
 *
 * 当队列满了以后，存储元素的线程需要备阻塞直到队列可以添加数据
 */
public class BlockingQueue {
    private ArrayList<String> container = new ArrayList<>();;
    private Lock lock = new ReentrantLock();
    private Condition emputyCondition = lock.newCondition();
    private Condition fullCondition = lock.newCondition();
    private int num ;
    public BlockingQueue(int num) {
        num = num;
    }

    public String take(){
        try {
            lock.lock();
            while(container.isEmpty()){
                emputyCondition.await();
            }
           String e  = container.remove(0);
            System.out.println("消費数据:"+e);
            fullCondition.signal();
            return e;
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
                lock.unlock();
        }
        return null;
    }

    public void put(String str) {
        try{
            lock.lock();
            while(container.size() >= 5) {
                fullCondition.await();
            }
            System.out.println("放入数据:"+str);
            container.add(str);
            emputyCondition.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        BlockingQueue blockingQueue = new BlockingQueue(5);
        new Thread(()->{
            for (int i = 0; i < 100; i++) {
                blockingQueue.put(i+"");
            }
        }).start();
        new Thread(()->{
            for (int i = 0; i < 100; i++) {
                blockingQueue.take();
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
